package fun.stgoder.test1;

public class TestThreadLocal {
    public static void main(String[] args) {
        ThreadLocal<String> stringThreadLocal = new ThreadLocal<>();
        stringThreadLocal.set(Thread.currentThread().getName());

        User user = new User();
        user.setUid("uid0000");
        user.setUsername("user0000");
        SimpleUserStore.set(user);

        for (int i = 0; i < 3; i++) {
            final int j = i;
            new Thread(() -> {
                stringThreadLocal.set(Thread.currentThread().getName());

                User user1 = new User();
                user1.setUid(Thread.currentThread().getName());
                user1.setUsername(Thread.currentThread().getName());
                SimpleUserStore.set(user1);

                TestUtil.sleepSeconds(3);

                System.out.println(stringThreadLocal.get());
                System.out.println(SimpleUserStore.get());
            }).start();
        }

        TestUtil.sleepSeconds(3);

        System.out.println(stringThreadLocal.get());

        System.out.println(SimpleUserStore.get());
    }
}

class SimpleUserStore {
    private static ThreadLocal<User> userThreadLocal = new ThreadLocal<>();

    public static void set(User user) {
        userThreadLocal.set(user);
    }

    public static User get() {
        return userThreadLocal.get();
    }

    public static void remove() {
        userThreadLocal.remove();
    }
}

class User {
    private String uid;
    private String username;
    private String password;

    @Override
    public String toString() {
        return "uid: " + uid + ", username: " + username + ", password: " + password;
    }

    public String getUid() {
        return uid;
    }

    public void setUid(String uid) {
        this.uid = uid;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}
